<template>
  <a-layout class="layout">
    <!-- 侧边栏 -->
    <a-layout-sider
      v-model:collapsed="collapsed"
      class="sider"
      :trigger="null"
      collapsible
      :width="200"
    >
      <div class="logo">
        <img src="@/assets/logo.svg" alt="logo" />
        <span v-show="!collapsed">农产品供销平台</span>
      </div>
      <a-menu
        v-model:selectedKeys="selectedKeys"
        v-model:openKeys="openKeys"
        theme="dark"
        mode="inline"
      >
        <!-- 首页菜单项 - 只对农户显示 -->
        <a-menu-item key="/" v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER">
          <template #icon>
            <home-outlined />
          </template>
          <router-link to="/">首页</router-link>
        </a-menu-item>

        <!-- 商品管理菜单 - 对管理员和农户都显示 -->
        <a-sub-menu key="product">
          <template #icon>
            <shopping-outlined />
          </template>
          <template #title>商品管理</template>
          <a-menu-item key="/products">
            <router-link to="/products">商品列表</router-link>
          </a-menu-item>
          <a-menu-item key="/categories" v-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
            <router-link to="/categories">分类管理</router-link>
          </a-menu-item>
        </a-sub-menu>

        <!-- 订单管理菜单 - 对所有用户可见 -->
        <a-sub-menu key="order">
          <template #icon>
            <shopping-cart-outlined />
          </template>
          <template #title>订单管理</template>
          <a-menu-item key="/order">
            <router-link to="/order">订单列表</router-link>
          </a-menu-item>
          <a-menu-item key="/after-sales">
            <router-link to="/after-sales">售后管理</router-link>
          </a-menu-item>
        </a-sub-menu>

        <!-- 营销管理菜单 - 对管理员显示 -->
        <a-sub-menu key="promotion" v-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
          <template #icon>
            <gift-outlined />
          </template>
          <template #title>营销管理</template>
          <a-menu-item key="/coupons">
            <router-link to="/coupons">优惠券管理</router-link>
          </a-menu-item>
          <a-menu-item key="/user-coupons">
            <router-link to="/user-coupons">用户优惠券</router-link>
          </a-menu-item>
          <a-menu-item key="/carousel">
            <router-link to="/carousel">轮播图管理</router-link>
          </a-menu-item>
        </a-sub-menu>

        <!-- 用户管理菜单 - 对管理员显示 -->
        <a-menu-item key="/users" v-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
          <template #icon>
            <user-outlined />
          </template>
          <router-link to="/users">用户管理</router-link>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>

    <a-layout>
      <!-- 顶部 -->
      <a-layout-header class="header">
        <menu-unfold-outlined
          v-if="collapsed"
          class="trigger"
          @click="() => (collapsed = !collapsed)"
        />
        <menu-fold-outlined
          v-else
          class="trigger"
          @click="() => (collapsed = !collapsed)"
        />
        <div class="right">
          <!-- 消息通知 -->
          <a-badge :count="notificationStore.unreadCount" :offset="[-8, 8]" class="notification-badge">
            <a-dropdown
              :trigger="['click']"
              placement="bottomRight"
              overlayClassName="notification-dropdown"
            >
              <div class="notification-trigger">
                <BellOutlined class="notification-icon" />
              </div>

              <template #overlay>
                <a-menu class="notification-menu">
                  <div class="notification-header">
                    <h3>消息通知</h3>
                    <a-button
                      type="link"
                      size="small"
                      @click="notificationStore.markAllAsRead"
                    >
                      全部已读
                    </a-button>
                    <a-button
                      type="dashed"
                      size="small"
                      @click="notificationStore.removeAll"
                    >
                      全部删除
                    </a-button>
                  </div>

                  <template v-if="notificationStore.notifications.length === 0">
                    <a-menu-item class="empty-notice">
                      <a-empty
                        :image="emptyNewsImage"
                        description="暂时没有新消息"
                      />
                    </a-menu-item>
                  </template>

                  <template v-else>
                    <div class="notification-list">
                      <a-menu-item
                        v-for="(msg, index) in notificationStore.notifications"
                        :key="index"
                        class="message-item"
                        :class="{ 'unread': !msg.read }"
                      >
                        <div class="message-content">
                          <div class="message-header">
                            <span class="status-dot" :style="{ backgroundColor: getStatusColor(msg.type) }"></span>
                            <span class="message-type">{{ getMessageTypeText(msg.type) }}</span>
                            <span class="message-time">{{ formatTimeAgo(msg.timestamp) }}</span>
                          </div>
                          <div class="message-body">
                            {{ msg.content }}
                          </div>
                          <div class="message-actions">
                            <a-button
                              type="link"
                              size="small"
                              @click.stop="notificationStore.removeNotification(index)"
                            >
                              <DeleteOutlined /> 删除
                            </a-button>
                            <a-button
                              v-if="!msg.read"
                              type="link"
                              size="small"
                              @click.stop="notificationStore.markAsRead(index)"
                            >
                              <CheckOutlined /> 标为已读
                            </a-button>
                          </div>
                        </div>
                      </a-menu-item>
                    </div>
                  </template>
                </a-menu>
              </template>
            </a-dropdown>
          </a-badge>

          <!-- 用户头像下拉菜单 -->
          <a-dropdown class="user-dropdown">
            <a class="user-dropdown-trigger">
              <a-avatar
                :src="userStore.userInfo?.avatarUrl || defaultAvatar"
                class="user-avatar"
                @error="handleAvatarError"
              >
                {{ userStore.userInfo?.userName?.charAt(0)?.toUpperCase() }}
              </a-avatar>
              <span class="username">{{ userStore.userInfo?.userName }}</span>
              <DownOutlined class="dropdown-arrow" />
            </a>
            <template #overlay>
              <a-menu class="user-menu">
                <a-menu-item class="menu-item" @click="router.push('/profile')">
                  <UserOutlined class="menu-icon" />
                  <span class="menu-text">个人中心</span>
                </a-menu-item>
                <a-menu-divider class="menu-divider" />
                <a-menu-item class="menu-item" @click="handleLogout">
                  <LogoutOutlined class="menu-icon" />
                  <span class="menu-text">退出登录</span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-layout-header>

      <!-- 内容区域 -->
      <a-layout-content class="content">
        <router-view></router-view>
      </a-layout-content>

      <!-- 底部 -->
      <a-layout-footer class="footer">
        <p>农产品供销平台后台  毕设非商用 请勿填写真实信息</p>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { USER_ROLE } from '@/constants/user'
import { useNotificationStore } from '@/stores/notification'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  HomeOutlined,
  ShoppingOutlined,
  AppstoreOutlined,
  UserOutlined,
  LogoutOutlined,
  ShoppingCartOutlined,
  BellOutlined,
  DownOutlined,
  CustomerServiceOutlined,
  DeleteOutlined,
  CheckOutlined,
  GiftOutlined,
  CreditCardOutlined
} from '@ant-design/icons-vue'
import { formatTimeAgo } from '../utils/date.ts'
import { useWebSocketStore } from '@/stores/WebSocket.ts'
import emptyNewsImage from '@/assets/emptyNews.png'
import defaultAvatar from '@/assets/default.jpg'

const url = import.meta.env.VITE_NEWS_WEBSOCKET_URL
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const notificationStore = useNotificationStore()
const websocketStore = useWebSocketStore()

const collapsed = ref(false)
const selectedKeys = computed(() => [route.path])
// 添加控制二级菜单展开的状态
const openKeys = ref<string[]>([])

// 监听路由变化，自动展开当前路由所在的子菜单
watch(() => route.path, (path) => {
  if (path.startsWith('/product')) {
    openKeys.value = ['product']
  } else if (path.startsWith('/order') || path.startsWith('/after-sales')) {
    openKeys.value = ['order']
  } else if (path.startsWith('/coupon') || path.startsWith('/user-coupon')) {
    openKeys.value = ['promotion']
  }
}, { immediate: true })

// 监听折叠状态，当折叠时关闭所有子菜单
watch(() => collapsed.value, (val) => {
  if (val) {
    openKeys.value = []
  } else {
    // 当展开时，根据当前路由自动展开对应的子菜单
    const path = route.path
    if (path.startsWith('/product')) {
      openKeys.value = ['product']
    } else if (path.startsWith('/order') || path.startsWith('/after-sales')) {
      openKeys.value = ['order']
    } else if (path.startsWith('/coupon') || path.startsWith('/user-coupon')) {
      openKeys.value = ['promotion']
    }
  }
})

const siderWidth = computed(() => collapsed.value ? '80px' : '200px')

// 使用computed获取token，确保响应式更新
const token = computed(() => userStore.token)

const handleLogout = () => {
  userStore.clearToken()
  router.push('/login')
}

// 添加连接状态检查
let connectionCheckInterval: ReturnType<typeof setInterval> | null = null

// 创建WebSocket连接的函数
const createWebSocketConnection = () => {
  // 确保token存在且正确拼接到URL中
  if (token.value) {
    const wsUrl = `${url}${token.value}`

    websocketStore.createConnection(
      'notification', // 唯一 key
      wsUrl,
      (event) => {
        const message = JSON.parse(event.data)
        notificationStore.addNotification({
          type: message.messageType,
          content: message.content,
          timestamp: new Date().getTime()
        })
      }
    )
    return true
  } else {
    console.error('[WebSocket] 无法创建连接: token不存在')
    return false
  }
}

// 在onMounted末尾添加定期检查连接状态的逻辑
onMounted(async () => {
  await userStore.fetchUserInfo()

  // 尝试创建连接
  createWebSocketConnection()

  // 定期检查连接状态
  connectionCheckInterval = setInterval(() => {
    const state = websocketStore.getConnectionState('notification')
    if (state === WebSocket.CLOSED) {
      console.log('[WebSocket] 检测到连接已关闭，尝试重新连接...')
      createWebSocketConnection()
    }
  }, 30000) // 每30秒检查一次
})

// 监听token变化，当token变化时重新建立连接
watch(() => token.value, (newToken) => {
  if (newToken) {
    console.log('[WebSocket] 检测到token变化，尝试建立连接')
    // 先关闭旧连接
    websocketStore.closeConnection('notification')
    // 创建新连接
    createWebSocketConnection()
  }
}, { immediate: true })

// 组件卸载时关闭连接
onUnmounted(() => {
  websocketStore.closeConnection('notification')
  if (connectionCheckInterval) {
    clearInterval(connectionCheckInterval)
  }
})

// 添加消息类型文本函数
const getMessageTypeText = (type: string) => ({
  order: '订单通知',
  stock: '库存预警',
  system: '系统消息',
  audit: '审核通知',
  other: '其他通知'
})[type] || '其他通知'

// 添加消息类型颜色函数
const getStatusColor = (type: string) => ({
  order: '#722ed1',
  stock: '#fa8c16',
  system: '#52c41a',
  audit: '#13c2c2',
  other: '#1890ff'
})[type] || '#1890ff'

// 在 script 部分添加错误处理函数
const handleAvatarError = (e: Event) => {
  const imgElement = e.target as HTMLImageElement
  imgElement.src = <string>defaultAvatar
}
</script>


<style scoped>
.layout {
  min-height: 100vh;
}

.sider {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 10;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
}

.logo {
  height: 64px;
  padding: 16px;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
}

.logo img {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.logo span {
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.header {
  position: fixed;
  top: 0;
  right: 0;
  z-index: 9;
  width: calc(100% - v-bind(siderWidth));
  background: #fff;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.trigger {
  padding: 0 24px;
  font-size: 18px;
  cursor: pointer;
  transition: color 0.3s;
}

.trigger:hover {
  color: #1890ff;
}

.right {
  padding-right: 24px;
  display: flex;
  align-items: center;
  gap: 24px;
}

.notification-badge {
  margin-right: 20px;

  :deep(.ant-badge-count) {
    box-shadow: 0 0 0 1px #fff;
  }
}

.notification-trigger {
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: rgba(0, 0, 0, 0.025);
    border-radius: 50%;

    .notification-icon {
      color: #1890ff;
    }
  }
}

.notification-icon {
  font-size: 18px;
  color: rgba(0, 0, 0, 0.65);
  transition: color 0.2s;
}

.user-dropdown-trigger {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  transition: all 0.3s;

  &:hover {
    background: rgba(0, 0, 0, 0.025);
    border-radius: 4px;
  }
}

.user-avatar {
  background-color: #1890ff;
  margin-right: 8px;
}

.username {
  margin: 0 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.dropdown-arrow {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  transition: transform 0.3s;
}

.user-menu {
  min-width: 140px;
  padding: 8px 0;

  .menu-item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    transition: all 0.3s;

    &:hover {
      background: #f5f5f5;
    }
  }

  .menu-icon {
    font-size: 14px;
    margin-right: 12px;
    color: rgba(0, 0, 0, 0.65);
  }

  .menu-text {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
  }

  .menu-divider {
    margin: 4px 0;
  }
}

.content {
  margin-left: v-bind(siderWidth);
  margin-top: 64px;
  margin-bottom: 48px;
  min-height: calc(100vh - 112px);
  background: #f0f2f5;
}

.footer {
  position: fixed;
  bottom: 0;
  right: 0;
  z-index: 9;
  width: calc(100% - v-bind(siderWidth));
  text-align: center;
  background: #fff;
  padding: 12px;
}

:deep(.ant-avatar) {
  background-color: #1890ff;
}

.empty-notice {
  padding: 16px 24px;
  width: 300px;
  text-align: center;

  .ant-empty-image {
    margin-bottom: 8px;
  }

  .ant-empty-description {
    color: rgba(0, 0, 0, 0.45);
  }
}

.message-item {
  padding: 12px 24px;
  transition: all 0.3s;

  &:hover {
    background: #f5f5f5;
  }
}

.message-content {
  width: 100%;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.message-type {
  font-weight: 500;
  margin-left: 8px;
}

.message-time {
  margin-left: auto;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.message-body {
  color: rgba(0, 0, 0, 0.65);
  margin-bottom: 8px;
}

.message-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.notification-footer {
  text-align: center;
  padding: 8px 0;
  border-top: 1px solid #f0f0f0;
}

.notification-dropdown {
  .ant-dropdown-menu {
    padding: 0;
    border-radius: 8px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
  }
}

.notification-menu {
  width: 360px;
  max-height: 60vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .empty-notice {
    padding: 24px 0;

    .ant-empty-image {
      height: 80px;
      margin-bottom: 8px;
    }

    .ant-empty-description {
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .notification-list {
    flex: 1;
    overflow-y: auto;
  }

  .message-item {
    padding: 12px 24px;
    transition: all 0.2s;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    &.unread {
      background: #fafafa;
    }

    &:hover {
      background: #f5f5f5;
    }
  }

  .message-content {
    position: relative;
  }

  .message-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .status-dot {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 8px;
    }

    .message-type {
      font-size: 13px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
    }

    .message-time {
      margin-left: auto;
      font-size: 12px;
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .message-body {
    color: rgba(0, 0, 0, 0.65);
    font-size: 13px;
    line-height: 1.5;
    margin-bottom: 8px;
  }

  .message-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;

    .ant-btn {
      font-size: 12px;
      padding: 0 4px;
      height: auto;
    }
  }

  .notification-footer {
    border-top: 1px solid #f0f0f0;

    .ant-btn {
      color: rgba(0, 0, 0, 0.65);
      padding: 12px;

      &:hover {
        color: #1890ff;
      }
    }
  }
}
</style>
